/*
 * Copyright (C) Antonio Ramon Morcillo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package soft.xitxarello.su.data;

import java.util.ArrayList;
import java.util.List;

import soft.xitxarello.su.R;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

/**
 * This class holds the per-item data in our uninstallable application list
 * Loader and other fragments.
 */
public class App implements Parcelable {

    // Logging tag
    private final String TAG = "seasonsend";

    // An application package name.
    private String packageName;

    // An application name.
    private String name;

    /**
     * Default constructor.
     * 
     * @param packageName Name of the package that application is in.
     */
    public App(String packageName) {
        this.packageName = packageName;
    }

    /**
     * Constructor from Parcel.
     * 
     * @param in The bulk of the Parcel API revolves around reading and writing
     *            data of various types.
     */
    private App(Parcel in) {
        this.packageName = in.readString();
    }

    /**
     * Get the name of a particular application.
     * 
     * @see android.content.pm.ApplicationInfo
     * @param context Interface to global information about an application
     *            environment.
     * @return sName Human-readable name for a particular application.
     */
    public String getName(Context context) {
        String sName = "";
        ApplicationInfo info;

        try {
            info = context.getPackageManager().getApplicationInfo(this.packageName, 0);
            CharSequence label = info.loadLabel(context.getPackageManager());
            sName = label != null ? label.toString() : info.packageName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, "NameNotFoundException" + e.getMessage());
            Log.e(TAG, e.toString());
        }

        return sName;
    }

    /**
     * Get the art icon of a particular application.
     * 
     * @see android.content.pm.ApplicationInfo
     * @param context Interface to global information about an application
     *            environment.
     * @return Art Icon about a particular application as a drawable.
     */
    public Drawable getIcon(Context context) {
        Drawable dIcon = null;
        ApplicationInfo info;

        try {
            info = context.getPackageManager().getApplicationInfo(this.packageName, 0);
            dIcon = info.loadIcon(context.getPackageManager());
        } catch (NameNotFoundException e) {
            Log.e(TAG, "NameNotFoundException" + e.getMessage());
            Log.e(TAG, e.toString());
        }

        return dIcon;
    }

    /**
     * Get the version of a particular application.
     * 
     * @see android.content.pm.PackageInfo
     * @param context context Interface to global information about an
     *            application environment.
     * @return The version name of the package as a string.
     */
    public String getVersion(Context context) {
        String sVersion = "";
        PackageInfo pInfo = null;

        try {
            pInfo = context.getPackageManager().getPackageInfo(this.packageName,
                    PackageManager.GET_PERMISSIONS);

            if (pInfo.versionName != null) {
                sVersion = pInfo.versionName;
            } else
                sVersion = "0.0";

        } catch (NameNotFoundException e) {
            Log.e(TAG, "NameNotFoundException" + e.getMessage());
            Log.e(TAG, e.toString());
        }
        return sVersion;
    }

    /**
     * Get the description of a particular application.
     * 
     * @see android.content.pm.ApplicationInfo
     * @param context context Interface to global information about an
     *            application environment.
     * @return The description of a particular application as a string.
     */
    public String getDescription(Context context) {
        String sDescription = context.getString(R.string.no_description);
        ApplicationInfo info;

        try {
            info = context.getPackageManager().getApplicationInfo(this.packageName, 0);
            if (info.loadDescription(context.getPackageManager()) != null) {
                sDescription = (String) info.loadDescription(context.getPackageManager());
            }
        } catch (NameNotFoundException e) {
            Log.e(TAG, "NameNotFoundException" + e.getMessage());
            Log.e(TAG, e.toString());
        }

        return sDescription;
    }

    /**
     * Get the permissions of a particular application.
     * 
     * @param context context Interface to global information about an
     *            application environment.
     * @return Permissions from AndroidManifest file as a list of PermsGroup.
     */
    public List<PermsGroup> getPermissions(Context context) {

        // list with groups and permissions.
        List<PermsGroup> groups = new ArrayList<PermsGroup>();

        // Package information where the application is in.
        PackageInfo packInfo = null;

        // Array with all the permissions as String.
        String[] mRequestedPermissions = null;

        try {
            packInfo = context.getPackageManager().getPackageInfo(this.packageName,
                    PackageManager.GET_PERMISSIONS);
            mRequestedPermissions = packInfo.requestedPermissions;

        } catch (NameNotFoundException e) {
            Log.e(TAG, "NameNotFoundException" + e.getMessage());
            Log.e(TAG, e.toString());
        }

        // Control null permissions.
        if (mRequestedPermissions == null) {
            return groups;
        }

        // Create groups an their permissions.
        for (int i = 0; i < mRequestedPermissions.length; i++) {

            // Permission name.
            String permName = mRequestedPermissions[i];

            // We need PermissionInfo, PermissionGroupInfo and PermsGroup to
            // work.
            try {
                PermissionInfo tmpPermInfo = context.getPackageManager().getPermissionInfo(
                        permName, 0);
                PermissionGroupInfo tmpPermGrpInfo = context.getPackageManager()
                        .getPermissionGroupInfo(tmpPermInfo.group, 0);
                PermsGroup tmpGroup = new PermsGroup(context, tmpPermGrpInfo);

                // When group exists we need add new permission. When not, we
                // need create group and add permission.
                if (groups.contains(tmpGroup)) {
                    int j = groups.indexOf(tmpGroup);
                    tmpGroup = groups.get(j);
                    tmpGroup.addPermission(context, tmpPermInfo);
                    groups.set(j, tmpGroup);
                } else {
                    tmpGroup.addPermission(context, tmpPermInfo);
                    groups.add(tmpGroup);
                }

            } catch (NameNotFoundException e) {
                Log.w(TAG, "NameNotFoundException" + e.getMessage());
                Log.w(TAG, e.toString());
            }
        }

        // At last...
        return groups;
    }

    /**
     * Getter Method.
     * 
     * @return The package name where the app is in as a string.
     */
    public String getPackageName() {
        return packageName;
    }

    /**
     * Setter Method. Set the application name.
     * 
     * @param context Interface to global information about an application
     *            environment.
     */
    public void setName(Context context) {
        this.name = getName(context);
    }

    /**
     * Getter Method.
     * 
     * @return the application name as a string.
     */
    public String getName() {
        return name;
    }

    /**
     * Setter Method. Set the package name of the application.
     * 
     * @param packageName the packageName to set.
     */
    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    /**
     * Overrides a superclass method. Describe the kinds of special objects
     * contained in this Parcelable's marshalled representation.
     * 
     * @return a bitmask indicating the set of special object types marshalled
     *         by the Parcelable.
     */
    @Override
    public int describeContents() {
        return 0;
    }

    /**
     * Overrides a superclass method. Flatten this object in to a Parcel.
     * 
     * @param dest The Parcel in which the object should be written.
     * @param flags Additional flags about how the object should be written. May
     *            be 0 or PARCELABLE_WRITE_RETURN_VALUE.
     */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.packageName);
    }

    /**
     * Specialization of Parcelable.Creator that allows you to receive the
     * ClassLoader the object is being created in.
     */
    public static final Parcelable.Creator<App> CREATOR = new Parcelable.Creator<App>() {
        /**
         * Create a new instance of the Parcelable App class, instantiating it
         * from the given Parcel whose data had previously been written by
         * Parcelable.writeToParcel().
         * 
         * @param in The Parcel to read the object's data from.
         * @return Returns a new instance of the Parcelable App class.
         */
        public App createFromParcel(Parcel in) {
            return new App(in);
        }

        /**
         * Create a new array of the Parcelable App class.
         * 
         * @param size Size of the array.
         * @return Returns an array of the Parcelable App class, with every
         *         entry initialized to null.
         */
        public App[] newArray(int size) {
            return new App[size];
        }
    };
}
